package com.yq.master.controller;

import com.alibaba.fastjson.JSON;
import com.google.common.collect.Maps;
import com.yq.core.base.entity.BaseEntity;
import com.yq.core.base.service.BaseService;
import com.yq.core.entity.SysUserEntity;
import com.yq.core.json.BaseData;
import com.yq.core.util.Page;
import com.yq.core.util.Result;
import com.yq.core.constant.Constant;

import com.yq.master.bean.WebUserBean;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.util.Map;


/**
 * 
 * 文件名: BnEmployeeController.java
 * 创建人: yinquan
 * 创建日期: 2017-03-21 15:42:34
 * 描  述: 代码
 * 版本号： 1.0
 */
@Controller
@RequestMapping(value = "/base")
public abstract class BaseController {

    private static Logger logger = LoggerFactory.getLogger(BaseController.class);

	protected abstract BaseService getServcie();

	protected abstract String getJumpData();

	protected String uid;

	public Map<String, String> fieldMap = Maps.newHashMap();

    /**
     * 查询页面初始化
     * @param model
     * @param request
     * @return
     */
    @RequestMapping(value = "search",params="_m=init")
	public String searchInit(Model model, ServletRequest request) {
		return getJump(request);
	}
    /**
     * 新增页面初始化
     * @param model
     * @param request
     * @return
     */
    @RequestMapping(value = "insert",params="_m=init")
	public String insertInit(Model model, ServletRequest request) {
		return getJump(request);
	}
    /**
     * 更新页面初始化
     * @param model
     * @param request
     * @return
     */
    @RequestMapping(value = "update",params="_m=init")
	public String updateInit(Model model, ServletRequest request) {
		return getJump(request);
	}

    /**
     * 查询
     * @param model
     * @param request
     * @return
     */
	@RequestMapping(value = "search",params="_m=load")
	@ResponseBody
	public Object searchLoad(Model model, ServletRequest request) {
		Page page = getPage(request);
		Map<String, Object> parameters = Maps.newHashMap();
		return getServcie().paging(parameters, page);
	}
	/**
     * 新增
     * @param model
     * @param request
     * @return
     */
	@RequestMapping(value = "insert",params="_m=exec")
	@ResponseBody
	public Object insertExec(Model model, ServletRequest request) {
		Result result = isCheck(request);
//		if(!result.isPass()) {
//			return result;
//		}

		// 根据主键判断保存
		if (StringUtils.isBlank(getUid(request))) {
			getServcie().insert(createEntity(request));
		} else {
			//return updateExec(model, request);
		}

		return result;
	}
	/**
     * 编辑
     * @param model
     * @param request
     * @return
     */
	@RequestMapping(value = "update",params="_m=exec")
	@ResponseBody
	public Object updateExec(Model model, ServletRequest request) {
		Result result = isCheck(request);
		if(!result.isPass()) {
			return result;
		}
		// 根据主键判断更新
		if (StringUtils.isBlank(getUid(request))) {
			//return insertExec(model, request);
		} else {
			getServcie().update(createEntity(request));
		}
		return result;
	}
	/**
     * 删除
     * @param model
     * @param request
     * @return
     */
	@RequestMapping(value = "delete",params="_m=exec")
	@ResponseBody
	public Object deleteExec(Model model, ServletRequest request) {
		Result result = isCheck(request);
		if(!result.isPass()) {
			return result;
		}
		
		return "";
	}
	
	/**
     * 校验传入的参数
     * @param request
     * @return
     */
	public Result isCheck(ServletRequest request) {
		Result result = new Result();
		//Map<String, Object> config = BaseData.getConfig(request, this.getClass().getName());
		//if(config!=null) {
			// TODO 校验字段有效性
		//}
		
		result.setPass(true);
		
		return result;
	}

	// 获取跳转页面
	public String getJump(ServletRequest request) {
		//Map<String, Object> config = BaseData.getConfig(request, this.getClass().getName());
		Map<String, Object> config = (Map<String, Object>) JSON.parse(getJumpData());
		Object jump = config.get("jump");
		if(jump!=null) {
			return jump.toString();
		}
		return "";
	}

	// 创建对象
	public BaseEntity createEntity(ServletRequest request) {
		BaseEntity entity = null;
		try {
			Class entityClass = getServcie().getEntity();
			if (StringUtils.isBlank(getUid(request))) {
				entity = (BaseEntity) entityClass.newInstance();
			} else {
				entity = (BaseEntity) getServcie().findUniqueById(getUid(request));
			}
			Field[] fields = entityClass.getDeclaredFields();
			for (Field field : fields) {
				field.setAccessible(true);

				Class fieldType = field.getType(); // 获取字段类型
				String typeName = fieldType.getName(); // 获取属性名字
				String paramValue = request.getParameter(field.getName()); // 获取字段值

				if (typeName.startsWith("java.lang")) {
					Constructor constructor = fieldType.getConstructor(String.class); // 字符型
					if(paramValue!=null) {
						BeanUtils.setProperty(entity, field.getName(), constructor.newInstance(paramValue));
					}
				}
			}

			if(StringUtils.isBlank(getUid(request))) {
				Field createBy = entityClass.getDeclaredField("createBy");
				if (createBy != null) {
					createBy.setAccessible(true);
					createBy.set(entity, "system");
				}
			} else {
				Field updateBy = entityClass.getDeclaredField("updateBy");
				if (updateBy != null) {
					updateBy.setAccessible(true);
					updateBy.set(entity, "system");
				}
			}

			// 自定义赋值
			for (Map.Entry<String, String> entry : fieldMap.entrySet()) {
				BeanUtils.setProperty(entity, entry.getKey(), entry.getValue());
			}

		} catch (Exception e) {
			e.printStackTrace();
		}

		fieldMap.clear();

		return entity;
	}

	// 获取session中的用户信息
	public WebUserBean getWebUserBean(ServletRequest request) {
		HttpSession session = ((HttpServletRequest) request).getSession(false);
		return (session != null ? (WebUserBean) session.getAttribute(Constant.SESSION_KEY) : null);
	}

	// 获取uid
	public String getUid(ServletRequest request) {
		return request.getParameter("uid");
	}

	// 设置分页
	public Page getPage(ServletRequest request) {
		Page page = new Page();
		try {
			String nowPage = request.getParameter("page");
			String rows = request.getParameter("rows");

			if(StringUtils.isBlank(nowPage)) {
				page.setPageCurrent(1);
			} else {
				page.setPageCurrent(Integer.parseInt(nowPage));
			}

			if(StringUtils.isBlank(rows)) {
				page.setPageSize(10);
			} else {
				page.setPageSize(Integer.parseInt(rows));
			}
		} catch (Exception e) {
			e.printStackTrace();
			page.setPageCurrent(1);
			page.setPageSize(10);
		}
		return page;
	}

	/*@RequestMapping(value = "search",params="_m=init")
	public String searchInit(Model model,ServletRequest request) {
		Map<String, Object> parameters = Maps.newHashMap();
		Map<String, Object> config = (Map<String, Object>) JSON.parse(config());
		Map<String, Object> vail = (Map<String, Object>) config.get(getConfigByKey(request));

		if(true) {
			// 开始进行校验
			for(Iterator ite = vail.entrySet().iterator(); ite.hasNext();) {
				Map.Entry map = (Map.Entry) ite.next();
				String key = map.getKey().toString();
				Map<String, Object> data = (Map<String, Object>) map.getValue();
				System.out.println(data);

				// 获取值
				String value = request.getParameter(key);

				// 必填校验
				if(data.get("required")!=null 
					&& !data.get("required").toString().equals("false")
					&& StringUtils.isBlank(value)) {
					
					System.out.println("null");
				}

				if(data.get("length")!=null) {
					System.out.println(data.get("length").getClass());
				}


				// 长度校验

//				System.out.println(value.get("check").getClass());
//				System.out.println(value.get("length").getClass());
//				System.out.println(value.get("required").getClass());
//				System.out.println(value.get("mode").getClass());

			}
		}

		// 获取信息：分页信息、搜索条件

		// 调用service

		return "employee/employee-search";
	}*/


}
